% Simulink.importExternalCTypes('../CustomCode/SysIdParamLoading.h')

clear
clc

%% encode
% global SIN_TABLE_MAX_X
% global SIN_TABLE_MAX_Y
% global sin_tbl

SIN_TABLE_MAX_X = 2^13;%2^14
SIN_TABLE_MAX_Y = 32767;%2^14
SIN_TABLE_MAX_NUM_IN_ONE_LINE = 2048;

sin_tbl = zeros(SIN_TABLE_MAX_X,1);
sin_theta = zeros(SIN_TABLE_MAX_X,1);
theta = zeros(SIN_TABLE_MAX_X,1);
for i = 1:1:SIN_TABLE_MAX_X
    theta(i) = ((i-1)./SIN_TABLE_MAX_X)*2*pi;
    sin_theta(i) = sin(theta(i));
    sin_tbl(i) = round(SIN_TABLE_MAX_Y*sin(theta(i)));
end
sin_tbl;

%%printsin_tbl
disp("const int16 bm_sin_table[] = {");
str="";
for i = 1:1:SIN_TABLE_MAX_X
    str = str + sin_tbl(i) + ",";
    if mod(i,SIN_TABLE_MAX_NUM_IN_ONE_LINE)==0
        disp(str);
        str="";
    end
end
disp(str);
disp("};");
%%test
% theta_input = zeros(SIN_TABLE_MAX_X,1);
% theta_input = theta;
% sin_tbl_x = uint32(zeros(SIN_TABLE_MAX_X,1));
% sin_tbl_y = int32(zeros(SIN_TABLE_MAX_X,1));
% sin_bm_list = single(zeros(SIN_TABLE_MAX_X,1));
% %% edecode
% for i = 1:1:SIN_TABLE_MAX_X
%     sin_tbl_x(i) = uint32(theta_input(i)/(2*pi)*SIN_TABLE_MAX_X)+1;
%     sin_tbl_y(i) = sin_tbl(uint32(sin_tbl_x(i)));
%     sin_bm_list(i) = single(sin_tbl_y(i))/SIN_TABLE_MAX_Y;
%     sin_tbl(i) = round(SIN_TABLE_MAX_Y*sin(theta));
% end
sin_bm(-pi/4, sin_tbl, SIN_TABLE_MAX_X, SIN_TABLE_MAX_Y);

% sin_tbl_x;
% sin_tbl_y;
% sin_bm_list;
% disp(sin_theta + "            " + sin_bm_list + "          " + (sin_theta-sin_bm_list))


%%function
function value = sin_bm(theta, sin_tbl, SIN_TABLE_MAX_X, SIN_TABLE_MAX_Y)

    sin_tbl_x = mod(uint32(theta/(2*pi)*SIN_TABLE_MAX_X), SIN_TABLE_MAX_X)+1;
%     sin_tbl_x
    sin_tbl_y = int32(sin_tbl(uint32(sin_tbl_x)));
%     sin_tbl_y
    value = single(sin_tbl_y)/SIN_TABLE_MAX_Y;
%     value
end